package vip.zhenzicheng.jpa.base;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Optional;

/**
 * 公共服务实现类，所有service的实现类都应该实现
 *
 * @author zhenzicheng
 * @date 2023-04-17 16:36
 */
public abstract class BaseServiceImpl<T extends BaseAuditEntity, ID extends Number> implements BaseService<T, ID> {

    private JpaRepository<T, ID> repository;

    /**
     * 设置子类具体的 repository
     */
    @PostConstruct
    private void setRepository() {
        this.repository = getRepository();
    }

    /**
     * 获取子类dao
     */
    protected abstract JpaRepository<T, ID> getRepository();

    @Override
    public T saveOrUpdate(T e) {
        return repository.save(e);
    }

    @Override
    public List<T> saveAll(Iterable<T> var1) {
        return repository.saveAll(var1);
    }

    @Override
    public T findById(ID id) {
        if (repository.existsById(id)) {
            Optional<T> result = repository.findById(id);
            if (result.isPresent()) {
                return result.get();
            }
        }
        return null;
    }

    @Override
    public void deleteById(ID id) {
        repository.deleteById(id);
    }

    @Override
    public void deleteAll() {
        repository.deleteAll();
    }

    @Override
    public void deleteAllByIdInBatch(Iterable<ID> idList) {
        repository.deleteAllByIdInBatch(idList);
    }

    @Override
    public void cascadeDeleteAllByIdInBatch(Iterable<ID> idList) {
        for (ID id : idList) {
            repository.deleteById(id);
        }
    }

    @Override
    public List<T> findAll() {
        Sort sort = Sort.by(Sort.Direction.DESC, "updatedTime");
        return repository.findAll(sort);
    }


    @Override
    public Page<T> findAll(Pageable pageable) {
        return repository.findAll(appendDefaultSort(pageable));
    }

    @Override
    public void deleteAllInBatch(Iterable<T> var1) {
        repository.deleteAllInBatch(var1);
    }

    /**
     * 增加根据修改时间默认排序
     */
    protected Pageable appendDefaultSort(Pageable pageable) {
        Sort sort = pageable.getSort();
        Sort newSort = Sort.by(Sort.Direction.DESC, "updatedTime");
        Sort sort1 = sort.and(newSort);
        return PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), sort1);
    }
}
